<template>
  <div class="rec">
    <div class="title">
      <h2>人气推荐</h2>
    </div>
    <div class="rec-list-box">
      <div class="rec-list">
        <div class="rec-item" v-for="item in recommendList" :key="item.id">
          <router-link
            tag="div"
            :to="`/goodsdetail/${item.id}`"
            class="item-img"
            ><img :src="item.img" alt=""
          /></router-link>
          <div class="main">
            <p class="item-title line-ellipsis">{{ item.title }}</p>
            <div class="car-box">
              <span>￥{{ item.price }}</span>
              <a @click="addGoods(item.id, userId)">
                <van-icon name="shopping-cart-o" />
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRecommend } from "@/api/inedx";
export default {
  data() {
    return {
      recommendList: [],
      userId: "",
    };
  },
  methods: {
    async getRecommendList() {
      let { data } = await this.$http(getRecommend());
      this.recommendList = data.data;
    },
    addGoods(val, id) {
      if (this.userId == "") {
        this.$toast("请先进行登录");
      } else {
        this.$http
          .post("http://192.168.27.59/addGoodsCar", {
            id: val,
            userId: id,
          })
          .then(({ data }) => {
            if (data.code == 300) {
              this.$toast(data.message);
            }
            this.$toast(data.message);
          });
      }
    },
  },
  created() {
    let userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
    if (userInfo) {
      this.userId = userInfo.userId == null ? "" : userInfo.userId;
    }
    this.getRecommendList();
  },
};
</script>

<style lang="scss" scoped>
.rec {
  width: 100vw;
  background-color: #fff;
  padding-bottom: 0.625rem;
  .title {
    width: 100%;
    text-align: center;
    padding: 0.5rem 0;
    border-bottom: 1px solid #cecccc;
    h2 {
      font-size: 18px;
    }
  }
  .rec-list-box {
    width: 100vw;
    .rec-list {
      display: flex;
      flex-wrap: wrap;
      .rec-item {
        width: 50%;
        text-align: center;
        .item-img {
          img {
            width: 80%;
          }
        }
        .main {
          padding: 0.625rem;
          font-size: 14px;
          p {
            margin: 0.25rem 0;
          }
          .car-box {
            display: flex;
            justify-content: space-between;
            color: #56bb37;
          }
        }
      }
    }
  }
}
</style>
